package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.ListOfAwardsResponse
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentListOfAwardsBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterListOfAwards
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityParticipationPrize
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPassAwardsDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPassGroupDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPigeonRacing
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONArray
import org.json.JSONObject
import java.lang.reflect.Type


/**
 * @Author      : hxw
 * @Date        : 2024/5/29 17:25
 * @Describe    : 奖项里列表
 */
class FragmentListOfAwards : BaseFragment<OrgRaceViewModel, FragmentListOfAwardsBinding>() {

    private var passId: Int = 0
    private val mAdapter: AdapterListOfAwards by lazy { AdapterListOfAwards(arrayListOf()) }

    private val sharedViewModel: SharedViewModel by activityViewModels()

    override fun initView(savedInstanceState: Bundle?) {
        passId = arguments?.getInt("passId", 0)!!.toInt()

        onRefresh()

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter)
            .addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 15f)))

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh()
        }

        sharedViewModel.data.observe(viewLifecycleOwner) {
            passId = it.id
            onRefresh()
        }

        mAdapter.setOnItemGroupClickListener(object : AdapterListOfAwards.OnItemGroupClickListener {
            override fun onItemClick(projectId: Int, projectName: String, groupTitle: String, type: Int) {
                when (type) { // 1-团体赛 2-关赛 3-单只多关赛(鸽王) 4-单关单只
                    2 -> startActivity<ActivityParticipationPrize>("title" to projectName, "projectId" to projectId,"titleGroup" to groupTitle)
                    3 -> startActivity<ActivityPigeonRacing>("title" to projectName, "projectId" to projectId, "titleGroup" to groupTitle)
                    1 -> startActivity<ActivityPassGroupDetail>("title" to projectName, "projectId" to projectId, "titleGroup" to groupTitle)
                    4 -> startActivity<ActivityPassAwardsDetail>("title" to projectName, "projectId" to projectId, "titleGroup" to groupTitle)
                }
            }
        })
    }

    private fun onRefresh() {
        showLoading(getString(R.string.loading))
        mViewModel.getAppPassProjectList(passId.toString())
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取app关卡的项目列表  */
        mViewModel.appPassProjectResult.observe(viewLifecycleOwner) {
            if (mDatabind.includeList.swipeRefreshLayout.isRefreshing) {
                mDatabind.includeList.swipeRefreshLayout.isRefreshing = false
            }
            if (it != null) {
                // 创建Gson实例
                val gson = Gson()
                val data = gson.toJson(it)
                if (data.startsWith("{")) {
                    val jsonData = JSONObject(data)
                    if (jsonData.length() != 0) {
                        showEmptyView(isEmpty = false)
                        // 定义TypeToken以获取List<User>的类型
                        val userListType: Type = object : TypeToken<List<ListOfAwardsResponse?>?>() {}.type
                        // 将JSON字符串解析为List<User>
                        val it: List<ListOfAwardsResponse> = gson.fromJson(data, userListType)
                        mAdapter.setList(it)
                        mAdapter.notifyDataSetChanged()
                    } else {
                        showEmptyView(isEmpty = true)
                    }
                } else {
                    val jsonData = JSONArray(data)
                    if (jsonData.length() != 0) {
                        showEmptyView(isEmpty = false)
                        // 定义TypeToken以获取List<User>的类型
                        val userListType: Type = object : TypeToken<List<ListOfAwardsResponse?>?>() {}.type
                        // 将JSON字符串解析为List<User>
                        val it: List<ListOfAwardsResponse> = gson.fromJson(data, userListType)
                        mAdapter.setList(it)
                        mAdapter.notifyDataSetChanged()
                    } else {
                        showEmptyView(isEmpty = true)
                    }
                }
            } else {
                showEmptyView(isEmpty = true)
            }
        }
    }

    private fun showEmptyView(isEmpty: Boolean) {
        mDatabind.includeList.swipeRecyclerView.isVisible = !isEmpty
        mDatabind.includeEmptyView.llEmptyData.isVisible = isEmpty
    }

    companion object {
        fun newInstance(passId: Int): FragmentListOfAwards {
            val fragment = FragmentListOfAwards()
            val bundle = Bundle()
            bundle.putInt("passId", passId)
            fragment.arguments = bundle
            return fragment
        }
    }
}